package com.wtf.init;

import org.rpc.common.JSONSerializer;
import com.wtf.config.RpcDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.rpc.pojo.RpcRequest;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 11/10/2020
 */
@Component
public class RunRpcServer implements CommandLineRunner {

    @Resource
    private ChannelHandler userChannelHandler;

    public static final String HOST = "127.0.0.1";
    public static final Integer PORT = 9999;

    @Override
    public void run(String... args) throws Exception {
        start(HOST, PORT);
    }

    /**
     * 启动netty服务端
     *
     * @param host 主机名
     * @param port 端口
     * @throws InterruptedException 异常
     */
    private void start(String host, Integer port) throws InterruptedException {
        //创建2个线程池对象bossGroup workerGroup,当前这两个实例代表两个线程池，默认线程数为CPU核心数乘2
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //创建启动引导类,组装一些必要的组件
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //设置启动引导类
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        // 添加自定义解码器
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        // 添加自定义handler
                        pipeline.addLast(userChannelHandler);
                    }
                });

        //启动引导类端口绑定
        serverBootstrap.bind(host, port).sync();
        System.out.println("Custom RPC Server Start...");
    }
}
